<?php 
	header('Content-Type:text/html;charset=utf-8');
	$conn=mysqli_connect('localhost','root','');
	mysqli_select_db($conn,'php_ajax');
	mysqli_set_charset($conn,'utf8');
	
	$sql="SELECT * FROM article";
	$res=mysqli_query($conn,$sql);
	if(mysqli_num_rows($res)>0){
		while($arr=mysqli_fetch_assoc($res)){
			$art_data[]=$arr;
		}
	}
	$total=mysqli_num_rows($res);
	//$postData = file_get_contents('php://input', true);
	//$obj=json_decode($postData);
	//详细页
	$aid=!empty($_POST['aid'])?$_POST['aid']:1;
	$de_sql="SELECT * FROM article WHERE a_id=$aid";
	$de_res=mysqli_query($conn,$de_sql);
	if(mysqli_num_rows($de_res)>0){
		$de_data=mysqli_fetch_assoc($de_res);
	}
	$de_data['prev']='';
	$de_data['prev_title']='';
	$de_data['next']='';
	$de_data['next_title']='';
	if(isset($_POST['aid'])){
		$prev=$aid>1?$aid-1:null;
		$next=$aid<$total?$aid+1:null;
		if(!empty($prev)){
			$prev_sql="SELECT * FROM article WHERE a_id=$prev";
			$prev_res=mysqli_query($conn,$prev_sql);
			if(mysqli_num_rows($prev_res)>0){
				$prev_data=mysqli_fetch_assoc($prev_res);
			}
			$de_data['prev']=$prev;
			$de_data['prev_title']=$prev_data['a_title'];
		}
		if(!empty($next)){
			$next_sql="SELECT * FROM article WHERE a_id=$next";
			$next_res=mysqli_query($conn,$next_sql);
			if(mysqli_num_rows($next_res)>0){
				$next_data=mysqli_fetch_assoc($next_res);
			}
			$de_data['next']=$next;
			$de_data['next_title']=$next_data['a_title'];
		}
		
		
	}
	
	//update readnum
	if(isset($_POST['read'])){
		$read=$de_data['a_readnum']+1;
		$read_id=$de_data['a_id'];
		$read_sql="UPDATE article SET a_readnum='$read' WHERE a_id=$read_id";
		mysqli_query($conn,$read_sql);
	}
	//max_read
	$read_sql="SELECT * FROM article WHERE a_readnum>1 ORDER BY a_readnum DESC LIMIT 5";
	$read_res=mysqli_query($conn,$read_sql);
	if(mysqli_num_rows($read_res)>0){
		while($read_arr=mysqli_fetch_assoc($read_res)){
			$arr_maxread[]=$read_arr;
		}
	}
	//最近更新
	$lately_sql="SELECT * FROM article ORDER BY a_id DESC LIMIT 5";
	$lately_res=mysqli_query($conn,$lately_sql);
	if(mysqli_num_rows($lately_res)>0){
		while($lately_arr=mysqli_fetch_assoc($lately_res)){
			$lately[]=$lately_arr;
		}
	}
	$data=array(
		'art'=>$art_data,
		'detailed'=>$de_data,
		'aid'=>$aid,
		'read'=>$de_data['a_readnum'],
		'recommend'=>$arr_maxread,
		'lately'=>$lately,
	);
	echo json_encode($data);
?>